import json
import os

class ConfigManager:
    """
    配置管理类
    支持从文件或环境变量加载配置
    """

    def __init__(self, config_file='config.json'):
        self.config_file = config_file
        self.config = {}
        self.load_config()

    def load_config(self):
        """
        从配置文件或环境变量加载配置
        """
        # 尝试从配置文件加载
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.config = json.load(f)
            except Exception as e:
                print(f"从配置文件加载失败: {e}")

        # 从环境变量覆盖配置
        self.config['database'] = {
            'host': os.getenv('DB_HOST', self.config.get('database', {}).get('host', 'localhost')),
            'user': os.getenv('DB_USER', self.config.get('database', {}).get('user', 'root')),
            'password': os.getenv('DB_PASSWORD', self.config.get('database', {}).get('password', '123456')),
            'database': os.getenv('DB_NAME', self.config.get('database', {}).get('database', 'talent_frm_db')),
            'charset': os.getenv('DB_CHARSET', self.config.get('database', {}).get('charset', 'utf8mb4'))
        }

        self.config['redis'] = {
            'host': os.getenv('REDIS_HOST', self.config.get('redis', {}).get('host', 'localhost')),
            'port': int(os.getenv('REDIS_PORT', self.config.get('redis', {}).get('port', 6379))),
            'db': int(os.getenv('REDIS_DB', self.config.get('redis', {}).get('db', 0))),
            'password': os.getenv('REDIS_PASSWORD', self.config.get('redis', {}).get('password', None))
        }

        self.config['model'] = {
            'model_path': os.getenv('MODEL_PATH', self.config.get('model', {}).get('model_path', '../model/lightgbm_model.pkl'))
        }

    def get_database_config(self):
        """
        获取数据库配置
        """
        return self.config.get('database', {})

    def get_redis_config(self):
        """
        获取Redis配置
        """
        return self.config.get('redis', {})

    def get_model_config(self):
        """
        获取模型配置
        """
        return self.config.get('model', {})

    def get(self, key, default=None):
        """
        获取配置项
        """
        return self.config.get(key, default)
